package com.zq.api.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zq.common.annotation.Log;
import com.zq.common.annotation.RepeatSubmit;
import com.zq.common.constant.NumberConstants;
import com.zq.common.constant.SystemConstant;
import com.zq.common.core.domain.Result;
import com.zq.common.core.redis.RedisCache;
import com.zq.common.enums.BusinessEnum;
import com.zq.common.enums.BusinessType;
import com.zq.common.enums.OperatorType;
import com.zq.common.exception.base.BaseException;
import com.zq.common.utils.StringUtils;
import com.zq.server.api.dao.ActivityMapper;
import com.zq.server.api.domain.dto.ActivityListByTimeAndByAddressDto;
import com.zq.server.api.domain.dto.PublishActivityDto;
import com.zq.server.api.domain.entity.ApiActivity;
import com.zq.server.api.service.ApiActivityService;
import com.zq.server.core.sevcice.WebSocketServer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "活动接口")
@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController {

    private static final String TIME = "TIME";
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ApiActivityService activityService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private WebSocketServer socketServer;

    /**
     * 将日期字符串转换为Date对象
     *
     * @param dateString 日期字符串
     * @return 转换后的Date对象
     */
    public static Date convertToDate(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BaseException("200", "日期格式不正确：" + dateString);
        }
    }

    /**
     * 将Date对象格式化为指定格式的日期字符串
     *
     * @param date Date对象
     * @return 格式化后的日期字符串
     */
    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * is 模糊查询 根据地址 获取活动集合
     *
     * @param city
     * @return
     */
    @ApiOperation(" 根据地址 获取活动集合")
    @GetMapping("/getActivityInfoList")
    public Result<List<ApiActivity>> ListActivityInfo(String city) {
        // 判断返回数据是否为空
        if (city == null || city.isEmpty()) {
            log.error(SystemConstant.ACTIVITY_GEI_NFO_ERROR);
            throw new BaseException(SystemConstant.ACTIVITY_GEI_NFO_ERROR);
        }
        List<ApiActivity> activityList = activityService.ListActivityInfo(city);
        return Result.success(activityList);
    }

    @ApiOperation("获取ID活动信息")
    @GetMapping("/getActivityInfo")
    @Log(title = "Some Title")
    public Result<ApiActivity> getActivityInfo(@Param("aId") Integer aId) {
        if (StringUtils.isNull(aId)) {
            log.error("参数aId不能为空");
            log.error(SystemConstant.ACTIVITY_GEI_NFO_ERROR);
            throw new BaseException(SystemConstant.ACTIVITY_GEI_NFO_ERROR);
        }
        ApiActivity activity = activityMapper.getActivityInfo(aId);
        if (StringUtils.isNull(StringUtils.isNull(aId))) {
            log.error("未找到ID为{}的活动信息", aId);
            throw new BaseException(SystemConstant.RERUN_DATA_ERROR);
        }
        // 格式化活动时间
        return Result.success(activity);
    }

    @ApiOperation("发布活动")
    @PostMapping("/publishActivity")
    @Log(title = "发布活动", businessType = BusinessType.INSERT, operatorType = OperatorType.MOBILE)
    public Result publishActivity(@RequestBody PublishActivityDto publishActivityDto) {
        // 判断返回数据是否为空
        Boolean is = activityService.publishActivity(publishActivityDto);
        if (null == is) {
            log.error("发布活动失败");
            log.error(SystemConstant.PUBLISH_ACTIVITY_ERROR);
            throw new BaseException(SystemConstant.PUBLISH_ACTIVITY_ERROR);
        }

        return Result.success();
    }

    @ApiOperation("根据活动名称查询活动信息")
    @GetMapping("/getActivityByActivityName")
    public Result getActivityByActivityName(
        @RequestParam("activityName") @Validated @NotNull(message = "活动名称不能为空") String activityName) {
        // 从缓存中获取活动信息
        Object ActivityByActivityNameList = redisCache.getCacheList(activityName);
        if (StringUtils.isNull(ActivityByActivityNameList)) {
            // 缓存中不存在，从数据库查询
            List<ApiActivity> responseList = activityMapper.getActivityByActivityName(activityName);
            if (responseList == null || responseList.isEmpty()) {
                return Result.success();
            }
            // 设置缓存一天
            redisCache.setCacheList(activityName, responseList, NumberConstants.TWO_, TimeUnit.HOURS);
            return Result.success(responseList);
        } else {
            // 缓存中存在，直接返回缓存数据
            return Result.success(ActivityByActivityNameList);
        }

    }

    /**
     * @param dto 时间
     * @param dto 地址
     * @return java.util.List<ApiActivity> 活动集合
     * @作者 Caige
     * @日期 2024.3.24 15:02
     * @Description //TODO 15:02
     */
    @PostMapping("/getActivityListByTimeAndByAddress")
    @RepeatSubmit(interval = 3000)
    @ApiOperation("根据时间和地址查询活动信息")
    public Result getActivityListByTimeAndByAddress(@RequestBody @Validated ActivityListByTimeAndByAddressDto dto) {
        if (StringUtils.isBlank(dto.getTime()) || StringUtils.isBlank(dto.getCity())) {
            throw new BaseException(BusinessEnum.NOT_FOUND);
        }
        return Result.success(activityService.getActivityListByTimeAndByAddress(dto.getTime(), dto.getCity()));
    }

    /**
     * 获取用户参与过的集合
     * 
     * @作者 Caige
     * @日期 2024.3.27 13:14
     * @return com.zq.common.core.domain.Result
     */

    @GetMapping("/getUserPlayActivityList")
    @ApiOperation("获取用户参与过的集合")
    public Result getUserPlayActivityList() {
        return Result.success(activityService.getUserPlayActivityList());
    }
}
